#!/bin/sh

SERVICE_JAR="monitoring-resources-webPages-agent-1.1-SNAPSHOT.one-jar.jar"
OUTPUT_FILE="monitoring-resources-webPages-agent.out"
SERVICE_NAME="CFP WebPages Monitoring Agent"

getPID() {
    pgrep -f $SERVICE_JAR
}

start() {
    PID=$(getPID)
    if [ "$PID" == "" ]; then
	export LC_ALL=no_NO.UTF-8
	export NLS_LANG=NORWEGIAN_NORWAY.UTF-8

        java -jar $SERVICE_JAR >$OUTPUT_FILE &

	sleep 1
        PID=$(getPID)
	if [ "$PID" != "" ]; then
	    echo "$SERVICE_NAME started"
        else
    	    echo "$SERVICE_NAME startup failed"
	fi
    else
	echo "$SERVICE_NAME is already running; no action taken"
    fi
}

stop() {
    PID=$(getPID)
    if [ "$PID" != "" ]; then
        pkill -f $SERVICE_JAR
	sleep 1
        PID=$(getPID)
	if [ "$PID" == "" ]; then
	    echo "$SERVICE_NAME stopped"
        else
    	    echo "$SERVICE_NAME stopping failed"
	fi
    else
	echo "$SERVICE_NAME is already down; no action taken"
    fi
}

status() {
    PID=$(getPID)
    if [ "$PID" != "" ]; then
	echo "$SERVICE_NAME is running"
    else
	echo "$SERVICE_NAME is down"
    fi
}

dump() {
    tail -n 300 $OUTPUT_FILE 
}

case "$1" in

    'start')
	start
	;;

    'stop')
	stop
	;;

    'restart')
	stop
	start
	;;

    'status')
	status
	;;

    'dump')
	dump
	;;

    *)
	echo "Usage: $0 { start | stop | restart | status | dump }"
	exit 1
	;;
esac

exit 0
